<?php

namespace app\controller;

use app\service\UserService;
use support\Request;
use support\Response;

class  UserController extends Base
{

    //获取用户信息
    public function get_user_info(Request $request)
    {
        return json(apiSuccess($this->user));
    }

    //获取长连接
    public function websocket(): Response
    {
        $info = [
            'user_id' => $this->user_id,
            'u_tm' => time() + 60 * 60 * 24
        ];
        $token = base64_encode(json_encode($info));
        $url =  env('WEBSOCKET_URL')."?token=$token";
        return json(apiSuccess(['url' => $url]));

    }




    //修改用户昵称
    public function update_nickname(Request $request)
    {
        //昵称
        $nickname = $request->post('nickname', '');
        //昵称不能为空
        if (empty($nickname)) {
            return json(apiError('昵称不能为空'));
        }
        $res = (new UserService())->update_nickname($this->user, $nickname);
        return json($res);
    }


    //修改问题和答案
    public function modify_problem_answer(Request $request)
    {
        //问题
        $problem = $request->input('problem');
        //答案
        $answer = $request->input('answer');

       $res = (new UserService())->modify_problem_answer($this->user,$problem,$answer);

       return json($res);
    }

    //积分变动
    public function change_score(Request $request)
    {
        //积分
        $score = $request->post('score',0);
        //积分只能是正整数
        if(!is_numeric($score) || $score < 0){
            return json(apiError('积分只能是正整数'));
        }
        //类型 1 增加 2 减少
        $type = $request->post('type',1);
        $res = (new UserService())->change_score($this->user,$score,$type);
        return json($res);
    }

    //我的背包
    public function backpack(Request $request)
    {
        $res = (new UserService())->backpack($this->user);
        return json($res);
    }

    //上传语音消息
    public function upload_voice(Request $request)
    {
        $res = (new UserService())->upload_voice($this->user,$request);
        return json($res);
    }



}
